<template>
  <div class="container dark-theme">
    <!-- 头部导航栏 -->
    <div class="header">
      <div class="back-button" @click="goBack">
        <i class="el-icon-arrow-left"></i> 返回
      </div>
      <div class="title">房屋详情</div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <el-spinner></el-spinner>
      <span>加载中...</span>
    </div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="error">
      <p>{{ error }}</p>
      <el-button type="primary" @click="fetchHouseDetail">重试</el-button>
    </div>

    <!-- 主要内容区域 -->
    <div v-else class="main-content">
      <div class="product-info">
        <div class="product-image">
          <img :src="product.images" :alt="product.title">
        </div>
        <div class="product-details">
          <h2>{{ product.title }}</h2>
          <h3>{{ product.subTitle }}</h3>
          <div class="price">
            ¥{{ (product.currentPrice / 100).toFixed(2) }}/月
            <span class="original-price" v-if="product.originalPrice > product.currentPrice">
              ¥{{ (product.originalPrice / 100).toFixed(2) }}/月
            </span>
          </div>
          <div class="store-info">
            <i class="el-icon-shop"></i>
            <span>{{ product.ownerName || '未知房东' }}</span>
          </div>
          <div class="store-info">
            <i class="el-icon-shop"></i>
            <span>{{ product.ownerContact || '暂无联系方式' }}</span>
          </div>
          <div class="tags">
            <span v-if="product.currentPrice < product.originalPrice" class="tag special">特价</span>
            <span v-if="isNewHouse(product.createTime)" class="tag new">新房源</span>
            <span v-if="product.status === 1" class="tag hot">热租</span>
          </div>
<!--          &lt;!&ndash; 库存信息 &ndash;&gt;-->
<!--          <div class="stock-info">-->
<!--            <span>可用库存：{{ totalStock }} 套</span>-->
<!--          </div>-->
          <!-- 租赁时间选择 -->
          <div class="date-selector">
            <label>选择租赁时间：</label>
            <el-date-picker
              v-model="dateRange"
              type="monthrange"
              range-separator="至"
              start-placeholder="起始月"
              end-placeholder="结束月"
              :picker-options="pickerOptions"
              @change="handleDateChange"
            ></el-date-picker>
          </div>
          <!-- 年份选择 -->
          <div class="year-selector">
            <label>选择年份：</label>
            <el-select v-model="selectedYear" placeholder="请选择年份" @change="updateMonthStatus">
              <el-option
                v-for="year in availableYears"
                :key="year"
                :label="year"
                :value="year"
              ></el-option>
            </el-select>
          </div>
          <!-- 月份图标 -->
          <div class="month-icons">
            <div
              v-for="(month, index) in months"
              :key="index"
              :class="['month-icon', { 'disabled': !isAvailableMonthForYear(month) }, { 'selected': isSelectedMonth(month) }]"
              @click="toggleMonthSelection(month)"
            >
              <i :class="`el-icon-${monthIcons[index]}`"></i>
              <span>{{ month }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 房屋描述 -->
      <div class="description-section">
        <h3>房屋描述</h3>
        <p>{{ product.description || '暂无描述' }}</p>
      </div>

      <!-- 购买按钮 -->
      <div class="purchase-actions">
        <el-button
          type="danger"
          @click="buyNow"
          :disabled="product.status !== 1 || !isValidDateRange"
        >
          立即租赁
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import dayjs from 'dayjs';

export default {
  name: 'HouseDetail',
  data() {
    return {
      product: {
        id: null,
        title: '',
        subTitle: '',
        description: '',
        currentPrice: 0,
        originalPrice: 0,
        images: '',
        ownerId: null,
        ownerName: '',
        ownerContact:'',
        stock: 0,
        status: 0,
        createTime: '',
        checkinDates: []
      },
      imageBaseUrl: 'http://localhost:8089',
      loading: false,
      error: null,
      dateRange: [], // [起始月, 结束月]
      selectedYear: null,
      availableYears: [],
      months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
      monthIcons: ['calendar', 'calendar', 'calendar', 'calendar', 'calendar', 'calendar', 'calendar', 'calendar', 'calendar', 'calendar', 'calendar', 'calendar'],
      user: null
    };
  },
  computed: {
    pickerOptions() {
      return {
        disabledDate: (date) => this.isDisabledDate(date),
        shortcuts: [
          {
            text: '未来3个月',
            onClick(picker) {
              const start = dayjs().startOf('month').toDate();
              const end = dayjs().add(2, 'month').endOf('month').toDate();
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '未来6个月',
            onClick(picker) {
              const start = dayjs().startOf('month').toDate();
              const end = dayjs().add(5, 'month').endOf('month').toDate();
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      };
    },
    isValidDateRange() {
      return this.dateRange && this.dateRange.length === 2 && this.isValidRange(this.dateRange);
    },
    totalStock() {
      return this.product.checkinDates.reduce((sum, item) => sum + (item.stock || 0), 0);
    }
  },
  created() {
    this.fetchHouseDetail();
    this.initializeYears();
  },
  methods: {
    async fetchHouseDetail() {
      this.loading = true;
      this.error = null;
      try {
        const houseId = this.$route.params.id;
        const houseResponse = await axios.get(`/commodity/house/house/${houseId}`);
        if (!houseResponse.data.success) {
          throw new Error(houseResponse.data.errorMsg || '获取房屋详情失败');
        }
        const productData = Array.isArray(houseResponse.data.data)
          ? houseResponse.data.data[0]
          : houseResponse.data.data;
        if (!productData) {
          throw new Error('房屋数据为空');
        }

        let ownerName = '未知房东';
        let ownerContact='暂无联系方式';
        try {
          const ownerResponse = await axios.get(`/commodity/owner/${productData.ownerId}`);
          if (ownerResponse.data.success && ownerResponse.data.data) {
            ownerName = ownerResponse.data.data.name || `房东${productData.ownerId}`;
            ownerContact = ownerResponse.data.data.contact;
          }
        } catch (ownerError) {
          console.error('获取房东信息失败:', ownerError);
        }

        const timeResponse = await axios.get(`/commodity/house/houseInfo/${houseId}`);
        if (!timeResponse.data.success) {
          throw new Error(timeResponse.data.errorMsg || '获取房屋时间段信息失败');
        }
        const timeData = Array.isArray(timeResponse.data.data)
          ? timeResponse.data.data
          : [timeResponse.data.data];

        // Aggregate stock for duplicate checkin dates
        const aggregatedCheckinDates = [];
        const dateMap = new Map();
        timeData.forEach(item => {
          const date = dayjs(item.checkinDate).format('YYYY-MM-DD');
          if (dateMap.has(date)) {
            dateMap.set(date, dateMap.get(date) + (item.stock || 0));
          } else {
            dateMap.set(date, item.stock || 0);
          }
        });
        dateMap.forEach((stock, checkinDate) => {
          aggregatedCheckinDates.push({ checkinDate, stock });
        });

        this.product = {
          ...productData,
          images: productData.images
            ? productData.images.startsWith('http')
              ? productData.images
              : `${this.imageBaseUrl}${productData.images}`
            : '',
          ownerName,
          ownerContact,
          checkinDates: aggregatedCheckinDates
        };
        this.updateMonthStatus();
      } catch (error) {
        this.error = error.message || '网络错误，请稍后重试';
      } finally {
        this.loading = false;
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    isNewHouse(createTime) {
      if (!createTime) return false;
      const createDate = new Date(createTime);
      const now = new Date();
      const diffDays = (now - createDate) / (1000 * 60 * 60 * 24);
      return diffDays <= 7;
    },
    initializeYears() {
      const now = new Date();
      const currentYear = now.getFullYear();
      this.availableYears = [currentYear, currentYear + 1, currentYear + 2];
      this.selectedYear = currentYear;
    },
    isAvailableMonthForYear(month) {
      if (!this.selectedYear) return false;
      const monthIndex = this.months.indexOf(month) + 1;
      const dateStr = `${this.selectedYear}-${monthIndex.toString().padStart(2, '0')}-01`;
      const date = dayjs(dateStr).startOf('month');
      const now = dayjs().startOf('month');
      const checkinDate = this.product.checkinDates.find(d =>
        dayjs(d.checkinDate).format('YYYY-MM-DD') === date.format('YYYY-MM-DD')
      );
      return checkinDate && checkinDate.stock > 0 && !date.isBefore(now);
    },
    isSelectedMonth(month) {
      if (!this.dateRange || this.dateRange.length !== 2) return false;
      const monthIndex = this.months.indexOf(month) + 1;
      const year = this.selectedYear;
      const date = dayjs(`${year}-${monthIndex.toString().padStart(2, '0')}-01`).startOf('month');
      const start = dayjs(this.dateRange[0]).startOf('month');
      const end = dayjs(this.dateRange[1]).startOf('month');
      return !date.isBefore(start) && !date.isAfter(end);
    },
    isDisabledDate(date) {
      const formattedDate = dayjs(date).startOf('month').format('YYYY-MM-DD');
      const now = dayjs().startOf('month');
      const checkinDate = this.product.checkinDates.find(d =>
        dayjs(d.checkinDate).format('YYYY-MM-DD') === formattedDate
      );
      return !checkinDate || checkinDate.stock <= 0 || dayjs(formattedDate).isBefore(now);
    },
    isValidRange(range) {
      if (!range || range.length !== 2) return false;
      const [start, end] = range;
      const startDate = dayjs(start).startOf('month');
      const endDate = dayjs(end).startOf('month');
      if (endDate.isBefore(startDate)) return false;
      let current = startDate;
      while (!current.isAfter(endDate)) {
        const dateStr = current.format('YYYY-MM-DD');
        const checkinDate = this.product.checkinDates.find(d =>
          dayjs(d.checkinDate).format('YYYY-MM-DD') === dateStr
        );
        if (!checkinDate || checkinDate.stock <= 0 || current.isBefore(dayjs().startOf('month'))) {
          return false;
        }
        current = current.add(1, 'month');
      }
      return true;
    },
    updateMonthStatus() {
      if (!this.selectedYear) return;
      this.$forceUpdate(); // 强制更新月份状态
    },
    toggleMonthSelection(month) {
      if (!this.isAvailableMonthForYear(month)) return;
      const monthIndex = this.months.indexOf(month) + 1;
      const date = dayjs(`${this.selectedYear}-${monthIndex.toString().padStart(2, '0')}-01`);
      if (!this.dateRange || this.dateRange.length === 0) {
        this.dateRange = [date.toDate(), date.toDate()];
      } else if (this.dateRange.length === 2) {
        const start = dayjs(this.dateRange[0]).startOf('month');
        const end = dayjs(this.dateRange[1]).startOf('month');
        if (date.isSame(start)) {
          this.dateRange = [];
        } else if (date.isSame(end)) {
          this.dateRange = [start.toDate()];
        } else if (date.isAfter(start) && date.isBefore(end)) {
          this.dateRange = [start.toDate(), date.toDate()];
        } else if (date.isBefore(start)) {
          this.dateRange = [date.toDate(), end.toDate()];
        } else {
          this.dateRange = [start.toDate(), date.toDate()];
        }
      } else if (this.dateRange.length === 1) {
        const existing = dayjs(this.dateRange[0]).startOf('month');
        if (date.isBefore(existing)) {
          this.dateRange = [date.toDate(), existing.toDate()];
        } else {
          this.dateRange = [existing.toDate(), date.toDate()];
        }
      }
      this.handleDateChange(this.dateRange);
    },
    handleDateChange(range) {
      if (!range || range.length !== 2) {
        this.$message.warning('请选择有效的租赁时间段');
        return;
      }
      const [start, end] = range;
      const startDate = dayjs(start).startOf('month');
      const endDate = dayjs(end).startOf('month');
      if (endDate.isBefore(startDate)) {
        this.$message.warning('结束月份不能早于起始月份');
        this.dateRange = [];
        return;
      }
      if (!this.isValidRange(range)) {
        this.$message.warning('所选时间段包含不可租赁的月份');
        this.dateRange = [];
        return;
      }
      this.$message.success(`已选择租赁时间：${startDate.format('YYYY-MM')} 至 ${endDate.format('YYYY-MM')}`);
    },
    async buyNow() {
      try {
        if (this.product.status !== 1) {
          this.$message.warning('房屋已下架，无法租赁');
          return;
        }
        if (!this.isValidDateRange) {
          this.$message.warning('请选择有效的租赁时间段');
          return;
        }

        const { data: userData } = await axios.get('/users/user/basic', {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        if (!userData.success || !userData.data) {
          this.$message.error('获取用户信息失败：无有效数据');
          return;
        }
        this.user = userData.data;

        const userId = this.user.id;
        const houseId = this.$route.params.id;
        const [startDate, endDate] = this.dateRange;
        // 格式化为完整的 ISO 8601 格式
        const start = dayjs(startDate).startOf('month').format('YYYY-MM-DDTHH:mm:ss');
        const end = dayjs(endDate).startOf('month').format('YYYY-MM-DDTHH:mm:ss');
        const amount = dayjs(end).diff(dayjs(start), 'month') + 1;

        if (!houseId) {
          this.$message.error('房屋ID无效');
          return;
        }

        const { data } = await axios.post(
          `/commodity/house-order/houseInfo/${houseId}?userId=${userId}&amount=${amount}&startDate=${start}&endDate=${end}`,
          {},
          { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } }
        );

        if (data.success) {
          this.$message.success(`租赁成功，订单ID：${data.data.join(', ')}`);
          await this.fetchHouseDetail();
          this.dateRange = [];
        } else {
          this.$message.error(data.errorMsg || '租赁失败');
        }
      } catch (error) {
        this.$message.error('请求失败：' + (error.response?.data?.errorMsg || error.message));
      }
    }
  }
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: radial-gradient(ellipse at center, #001e3c 0%, #000 100%);
  color: #fff;
  font-family: 'Microsoft YaHei', sans-serif;
}

.header {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #002d52;
}

.back-button {
  cursor: pointer;
  color: #999;
  font-size: 16px;
}

.back-button:hover {
  color: #4fc3f7;
}

.title {
  margin-left: 20px;
  font-size: 20px;
  font-weight: bold;
}

.main-content {
  padding: 20px;
}

.product-info {
  background: rgba(0, 45, 82, 0.8);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.product-image {
  width: 100%;
  max-width: 400px;
  height: 300px;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.product-details {
  flex: 1;
}

.product-details h2 {
  margin: 0 0 10px 0;
  color: #fff;
}

.product-details h3 {
  margin: 0 0 10px 0;
  color: #e0e0e0;
  font-size: 18px;
}

.price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.original-price {
  color: #b0bec5;
  font-size: 16px;
  text-decoration: line-through;
  margin-left: 10px;
}

.store-info {
  color: #b0bec5;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.store-info i {
  margin-right: 5px;
}

.stock-info {
  color: #4fc3f7;
  margin-bottom: 10px;
  font-size: 16px;
}

.tags {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.tag.special {
  background: #f56c6c;
  color: #fff;
}

.tag.new {
  background: #67c23a;
  color: #fff;
}

.tag.hot {
  background: #e6a23c;
  color: #fff;
}

.date-selector {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.date-selector label {
  color: #e0e0e0;
  font-size: 16px;
}

.year-selector {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.year-selector label {
  color: #e0e0e0;
  font-size: 16px;
}

.month-icons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.month-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 60px;
  height: 80px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.3s;
}

.month-icon i {
  font-size: 24px;
  margin-bottom: 5px;
}

.month-icon span {
  font-size: 14px;
  color: #fff;
}

.month-icon.disabled {
  background: rgba(0, 0, 0, 0.3);
  cursor: not-allowed;
  opacity: 0.6;
}

.month-icon.selected {
  background: #4fc3f7;
  color: #fff;
}

.month-icon:hover:not(.disabled) {
  background: rgba(79, 195, 247, 0.3);
}

.description-section {
  background: rgba(0, 45, 82, 0.8);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.description-section h3 {
  margin: 0 0 10px 0;
  color: #fff;
}

.description-section p {
  color: #e0e0e0;
  line-height: 1.6;
  margin: 0;
}

.purchase-actions {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.el-button {
  padding: 12px 30px;
}

.el-button--danger {
  background: #f56c6c;
  border: 1px solid #f56c6c;
  color: #fff;
}

.el-button--danger:hover:not(:disabled) {
  background: #f78989;
  border-color: #f78989;
}

.el-button:disabled {
  background: #909399;
  border-color: #909399;
  color: #fff;
  cursor: not-allowed;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  color: #4fc3f7;
}

.error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  color: #f56c6c;
}

.error p {
  margin-bottom: 20px;
}
</style>
